#include "serial.h"
#include "usart.h"
#include "freeRTOS.h"
#include "queue.h"

#define USARTx_INSTANCE USART2


extern xQueueHandle queueRx;


void vSerialPutString(char *pStr, uint16_t len)
{
    uint16_t ubSend = 0;
    
    while(ubSend < len)
    {
        /* Wait for TXE flag to be raised */
        while(!LL_USART_IsActiveFlag_TXE(USARTx_INSTANCE))
        {
        }

        /* If last char to be sent, clear TC flag */
        if(ubSend == (len - 1))
        {
            LL_USART_ClearFlag_TC(USARTx_INSTANCE);
        }

        /* Write character in Transmit Data register.
           TXE flag is cleared by writing data in DR register */
        LL_USART_TransmitData8(USARTx_INSTANCE, pStr[ubSend++]);
    }
}

void xSerialPutChar(char c)
{
    while(!LL_USART_IsActiveFlag_TXE(USARTx_INSTANCE))
    {
    }

    /* If last char to be sent, clear TC flag */
    LL_USART_ClearFlag_TC(USARTx_INSTANCE);

    LL_USART_TransmitData8(USARTx_INSTANCE, c);
}


void USART2_IRQHandler(void)
{
    portBASE_TYPE xHighPriorityTaskWoken = pdFALSE;
    char c;
    
    if(LL_USART_IsEnabledIT_RXNE(USARTx_INSTANCE) && LL_USART_IsActiveFlag_RXNE(USARTx_INSTANCE))
    {
        c = LL_USART_ReceiveData8(USARTx_INSTANCE);
        xQueueSendFromISR(queueRx, &c, &xHighPriorityTaskWoken);

        portYIELD_FROM_ISR(xHighPriorityTaskWoken);
    }
}



